﻿using HBKY.Shop.Common;
using HBKY.Shop.Common.Helper;
using HBKY.Shop.Common.Redis;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HBKY.Shop.Extensions.ServiceExtensions
{
    /// <summary>
    /// Redis缓存 启动服务
    /// </summary>
    public static class RedisCacheSetup
    {
        public static void AddRedisCacheSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            services.AddTransient<IRedisBasketRepository, RedisBasketRepository>();

            // 配置启动Redis服务，虽然可能影响项目启动速度，但是不能在运行的时候报错，所以是合理的
            services.AddSingleton<ConnectionMultiplexer>(sp =>
            {
                if (Appsettings.Option("ConnectionStrings", "RedisConnection", "IsSentinel").ObjToBool())
                {
                    //获取连接字符串
                    var redisConnection = Appsettings.Option("ConnectionStrings", "RedisConnection", "RedisConnectionString");
                    var sentinels = Appsettings.OptionArray("ConnectionStrings", "RedisConnection", "Sentinels");
                    ConfigurationOptions sentinelConfig = new ConfigurationOptions();
                    sentinels.ToList().ForEach(o => { sentinelConfig.EndPoints.Add(o); });
                    //这行在sentinel模式必须加上
                    sentinelConfig.TieBreaker = string.Empty;
                    sentinelConfig.CommandMap = CommandMap.Sentinel;
                    ConnectionMultiplexer sentinelConnection = ConnectionMultiplexer.SentinelConnect(sentinelConfig);
                    ConfigurationOptions masterConfig = new ConfigurationOptions { ServiceName = redisConnection, ResolveDns = true, Password = "", };
                    var redisMasterConnection = sentinelConnection.GetSentinelMasterConnection(masterConfig);//Console.Out
                    return redisMasterConnection;
                }
                else
                {
                    string redisConfiguration = Appsettings.Option("ConnectionStrings", "RedisConnection", "RedisConnectionString");

                    var configuration = ConfigurationOptions.Parse(redisConfiguration, true);

                    configuration.ResolveDns = true;

                    return ConnectionMultiplexer.Connect(configuration);
                }
            });

        }
    }
}
